package com.server;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

public class CreateQRCodeString extends HttpServlet {

	/**
	 * 生成二维码字符串
	 * 接收cid，times
	 * 更新数据库，qrcode、times、date
	 * 返回qrCode
	 */
	private String cid;
	private String times;
	private String qrCode = "";
	//尾随随机数位数
	private static final int RANDOME_GRADE = 5;

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		PrintWriter out = response.getWriter();
		//获取课程号和点名次数字符串
		cid = request.getParameter("cid");
		times = request.getParameter("times");

		if(cid != null && !cid.equals("") && times != null && !times.equals("")){
			//二维码的组成 = cid + times + randomCode
			int randomcode = 0;
			//获取RANDOME_GRADE位的随机数
			randomcode = (int) ((Math.random() * 9 + 1) * Math.pow(10, RANDOME_GRADE - 1));
			//合成得到qrCode
			qrCode = randomcode + cid + times;

			//数据库操作，添加二维码
			System.out.println("qrCode内容是：" + qrCode);
			//记录系统时间
			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
			String date = dateFormat.format(new Date());
			//更新数据库，记录点名时间和二维码
			String sql = "UPDATE courses SET qrcode = '"+qrCode+"' , time_count = "+ times +" , time_"+times+" = '"+ date +"' WHERE cid = '"+cid+"';";
			System.out.println("sql内容是：" + sql);
			DBTools db = new DBTools();
			db.update(sql);
			db.close();

			out.println(qrCode);
		}else{
			out.println("ERROR!");
		}
		out.flush();
		out.close();
	}


	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
